﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using EMC;

namespace CHAPServer
{
    internal class User
    {
        private string username;
        private string key;

        public User(string user, string hash)
        {
            username = user;
            key = hash;
        }

        public string getUsername() { return username; }
        public string getHashKey() { return key; }
    }

    public static class CHAP
    {
        static object[] Users = new object[255];
        static int index = 0;
        static UserManagement userManagement;

        public static string Challenge(string username)
        {
            Random Rand = new Random();
            byte randB = (byte)Rand.Next(255);

            //  Create the challenge key from the date and random number
            string key = DateTime.Now.ToString() + randB;

            //  Encrypt Key
            string HashKey = Util.Hash(key);

            //  Store username and corresponding challenge key
            Users[index] = new User(username, HashKey);

            return HashKey;
        }

        public static string HandShake(string username, string UserKey)
        {
            userManagement = new UserManagement();

            string tempPass = userManagement.GetUserPassword(username);

            foreach (User user in Users)
            {
                if (user.getUsername() == username)
                {
                    string AuthKey = Util.Hash(tempPass + user.getHashKey());
                    if (UserKey == AuthKey)
                    {
                        return "1";
                    }
                }
            }
            return "0";
        }
    }
}